package it.traveldreamWeb.customer;

import it.traveldream.beans.BookingManagerInterface;
import it.traveldream.exceptions.InvalidReservationException;
import it.traveldream.exceptions.ProductNotFoundException;
import it.traveldream.exceptions.ProductSoldOutException;
import it.traveldreamWeb.authentification.PublicBean;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

@ManagedBean(name="homeBean")
@ViewScoped
public class HomeBean {
	
	private String successMessage;
	private String joinSuccess;
	private String invitationLink;
	private String error;
	
	@ManagedProperty(value="#{reservationBean}")
	private ReservationBean session;
	
	@ManagedProperty(value="#{publicBean}")
	private PublicBean publicSession;
	
	@EJB
	private BookingManagerInterface bookingManager;
	
	public void initHome(){
		this.setJoinSuccess("");
		this.session.cleanSession();
		
		if (this.publicSession.getReservation() != null){
			try{
				this.bookingManager.book(this.publicSession.getReservation(), false);
				this.setJoinSuccess("Congratulations. You have joined your friend's travel!");
			} catch (ProductNotFoundException e) {
				this.setError("Internal error. Some invalid product?");
			} catch (ProductSoldOutException e) {
				this.setError("Sorry. Sold out");
			} catch (InvalidReservationException e) {
				this.setError("Invalid request. Try again please");
			} catch (Exception e){
				this.setError("Internal error. Start over please");
			} finally {
				this.publicSession.clean();;
			}
		}
	}

	public String getSuccessMessage() {
		return this.successMessage;
	}

	public void setSuccessMessage(String successMessage) {
		this.successMessage = successMessage;
	}

	public String getJoinSuccess() {
		return this.joinSuccess;
	}

	public void setJoinSuccess(String joinSuccess) {
		this.joinSuccess = joinSuccess;
	}

	public String getInvitationLink() {
		return this.invitationLink;
	}

	public void setInvitationLink(String invitationLink) {
		this.invitationLink = invitationLink;
	}

	public void setSession(ReservationBean session) {
		this.session = session;
	}

	public void setPublicSession(PublicBean publicSession) {
		this.publicSession = publicSession;
	}

	public String getError() {
		return this.error;
	}

	public void setError(String error) {
		this.error = error;
	}
	
	public String getUsername(){
		return this.session.getCustomer().getUsername();
	}
}
